<template>
    <div class="common-layout">
      <el-container>
        <el-header>
          <el-header class="header-container">
            <div class="logo">
              <img src="../img/yz.webp" alt="永泽游戏网" />
              <span class="yz">永泽游戏网 - 管理员后台</span>
            </div>
            <div class="header-right">
              <el-button type="danger" @click="logout">退出登录</el-button>
            </div>
          </el-header>
        </el-header>
        <el-container>
          <el-aside width="200px">
            <el-scrollbar>
              <el-menu default-active="2-1" class="admin-menu">
                <el-sub-menu index="2">
                  <template #title>
                    <el-icon><setting /></el-icon>
                    <span>管理员功能</span>
                  </template>
                  <el-menu-item-group>
                    <el-menu-item index="2-1">
                      <router-link to="/checkGames">审核游戏</router-link>
                    </el-menu-item>
                    <el-menu-item index="2-2">
                      <router-link to="/auditGames">管理游戏</router-link>
                    </el-menu-item>
                    <el-menu-item index="2-3">
                      <router-link to="/home">返回主页</router-link>
                    </el-menu-item>
                  </el-menu-item-group>
                </el-sub-menu>
              </el-menu>
            </el-scrollbar>
          </el-aside>
          <el-main>
            <el-card class="audit-card">
              <h2>待审核游戏列表</h2>
              <el-table :data="gameList" style="width: 100%" border stripe>
                <el-table-column prop="name" label="游戏名称" width="180" />
                <el-table-column prop="category" label="分类" width="120" />
                <el-table-column prop="developer" label="开发商" width="150" />
                <el-table-column prop="releaseDate" label="发布日期" width="150" />
                <el-table-column prop="description" label="简介" min-width="200" />
                <el-table-column label="封面" width="100">
                  <template #default="scope">
                    <el-image
                      style="width: 80px; height: 80px"
                      :src="scope.row.imageUrl"
                      fit="cover"
                      :preview-src-list="[scope.row.imageUrl]"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="300">
                  <template #default="scope">
                    <el-button
                      type="success"
                      size="small"
                      @click="approveGame(scope.row.id)"
                    >
                      通过
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      @click="rejectGame(scope.row.id)"
                    >
                      拒绝
                    </el-button>
                    <el-button type="success" @click="startGame(scope.row.id)" round>
                    <i class="el-icon-caret-right"></i> 查看游戏资源
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页 -->
              <el-pagination
                class="pagination"
                v-model:current-page="currentPage"
                :page-size="pageSize"
                layout="prev, pager, next, total"
                :total="totalGames"
                @current-change="handlePageChange"
              />
            </el-card>
          </el-main>
        </el-container>
      </el-container>
      <div v-if="showGame" class="game-content">
      <el-button type="primary" @click="showGame = false" class="back-button" round>
        <i class="el-icon-arrow-left"></i> 返回
      </el-button>
      <iframe :src="gameResources" width="100%" height="600px" frameborder="0" class="game-iframe"></iframe>
    </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted,reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import request from '../axios/request';
  import { useRouter } from 'vue-router';
  import { computed } from 'vue';
  import { useAuthStore } from '../stores/userStore';

const store = useAuthStore();
  
  const token = localStorage.getItem('token');
  const router = useRouter();
  const pageKey = computed(() => {
  const storedPageKey = sessionStorage.getItem('pageKey');
  return storedPageKey || `${router.path || '/game'}-${Math.random().toString(36).substr(2, 9)}`;
});
  const formInline = reactive({
  user: ''
})
  // 游戏列表数据
  const gameList = ref([]);
  const currentPage = ref(1);
  const pageSize = ref(15);
  const totalGames = ref(0);
  const gameResources = ref('');
  const showGame = ref(false);
  

  const startGame = async (gameId) => {
  try {
    const res = await request({
      url: `/games-url/show?id=${gameId}`,
      method: 'get',
    });
    if (res.status === 200) {
      gameResources.value = URL.createObjectURL(new Blob([res.data], { type: 'text/html' }));
      showGame.value = true;
    } else {
      console.error('获取游戏资源失败:', res.data.msg);
      ElMessage.error('加载游戏失败');
    }
  } catch (err) {
    console.error('请求失败:', err);
    ElMessage.error('请求失败，请检查网络');
  } 
};

  // 获取待审核游戏列表
  const fetchPendingGames = async () => {
    try {
      const response = await request({
        url: `/games-details/listPage`,
        method: 'post',
        data: {
      pageSize: pageSize.value,
      pageNum: currentPage.value,
      param: { name: formInline.user },
        },
        pageKey: pageKey.value,
      });
  
      if (response.data.code === 200) {
        gameList.value = response.data.data; // 假设返回数据结构为 { list: [], total: xx }
        totalGames.value = response.data.data.total;
      } else {
        ElMessage.error('获取待审核游戏失败');
      }
    } catch (err) {
      console.error('请求失败:', err);
      ElMessage.error('请求失败，请重试');
    }
  };
  
  // 通过审核
  const approveGame = async (gameId) => {
    try {
      const response = await request({
        url: `/games-details/approve?id=${gameId}`,
        method: 'post',
        pageKey: pageKey.value,
      });
  
      if (response.data.code === 200) {
        ElMessage.success('游戏已通过审核');
        fetchPendingGames(); // 刷新列表
      } else {
        ElMessage.error('审核通过失败');
      }
    } catch (err) {
      console.error('审核失败:', err);
      ElMessage.error('审核失败，请重试');
    }
  };
  
  // 拒绝审核
  const rejectGame = async (gameId) => {
    try {
      const response = await request({
        url: `/games-details/reject?id=${gameId}`,
        method: 'post',
        pageKey: pageKey.value,
      });
  
      if (response.data.code === 200) {
        ElMessage.success('游戏已被拒绝');
        fetchPendingGames(); // 刷新列表
      } else {
        ElMessage.error('拒绝审核失败');
      }
    } catch (err) {
      console.error('拒绝失败:', err);
      ElMessage.error('拒绝失败，请重试');
    }
  };
  
  // 切换分页
  const handlePageChange = (page) => {
    currentPage.value = page;
    fetchPendingGames();
  };
  
  const logout = () => {
  // 清除本地存储中的 token 或用户信息
  request({
    url: '/login/logout',
    method: 'get',
    pageKey: pageKey.value,
  })
    .then((res) => {
      if (res.data.code === 200) {
              // 提示用户退出成功
        ElMessage({
          message: '退出登录成功',
          type: 'success',
        });
        store.logout(pageKey.value);
        // 跳转到登录页面
        router.push('/');
      } else {
        ElMessage.error('退出登录失败');
      }
    })
    .catch((err) => {
      console.error(err);
      ElMessage.error('请求失败，请检查网络');
    });

};
  
  // 页面加载时获取数据
  onMounted(() => {
    fetchPendingGames();
  });
  </script>
  
  <style scoped>
  /* 复用用户上传页面的样式 */
  .common-layout {
    background: #f4f6f9;
    min-height: 100vh;
    padding-bottom: 50px;
  }
  
  .el-container {
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
  }
  
  .header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    background-color: #2c3e50;
    color: #fff;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
  }
  
  .header-container .logo {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .header-container .logo img {
    height: 50px;
  }
  
  .header-container .yz {
    font-size: 1.5rem;
    font-weight: bold;
  }
  
  .header-right {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  /* 管理员页面特定样式 */
  .audit-card {
    background: #fff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
    margin-top: 20px;
  }
  
  .audit-card h2 {
    font-size: 1.8rem;
    color: #2c3e50;
    margin-bottom: 20px;
    text-align: center;
  }
  
  .el-table {
    border-radius: 8px;
    overflow: hidden;
  }
  
  .el-table th {
    background-color: #3498db;
    color: #fff;
    font-weight: bold;
  }
  
  .el-table td {
    vertical-align: middle;
  }
  
  .el-table .el-button {
    margin-right: 10px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  /* 按钮样式 */
  .el-button[type="success"] {
    background-color: #2ecc71;
    border: none;
  }
  
  .el-button[type="success"]:hover {
    background-color: #27ae60;
  }
  
  .el-button[type="danger"] {
    background-color: #e74c3c;
    border: none;
  }
  
  .el-button[type="danger"]:hover {
    background-color: #c0392b;
  }
  
  /* 侧边栏菜单 */
  .admin-menu .el-menu-item a {
    text-decoration: none;
    color: inherit;
  }
  
  .admin-menu .el-menu-item.is-active {
    background-color: #3498db;
    color: #fff;
  }
  </style>